using Microsoft.EntityFrameworkCore;
using Project_Schedule.Configures;
using Project_Schedule.Domain.BackGround.com.core.dto;
using Project_Schedule.Domain.BackGround.com.core.Interface;
using Project_Schedule.Domain.BackGround.com.core.utils;
using Project_Schedule.Domain.Request;
using Project_Schedule.Model;
using Project_Schedule.Model.Entities;
using Project_Schedule.Model.EntitiesHelper;

namespace Project_Schedule.Domain.BackGround.com.core.Service;

public class Bg_CreateUserService : IBackgroundCreateUser
{
    public async Task<JRequest> CreateUser(BackgroundCreateUser dto)
    {
        try
        {
            if (!CreateUserCheckout.BackgroundUserInfomationCheck(dto, out var message))
                throw new Exception(message);
            await using (var db = new DataDbContext())
            {
                var isHas = await db.BackgroundUsers?.FirstOrDefaultAsync(e =>
                    e.Account == dto.Account);
                if (isHas is not null)
                    throw new Exception("账户已存在");
                await db.BackgroundUsers.AddAsync(new Background_User
                {
                    Account = dto.Account,
                    UserName = dto.UserName,
                    CreateTime = DateTime.Now,
                    Password = RsaEncryptUtil.RSAEncrypt(dto.Password),
                    Auth = (Background_User_Auth_Enum)dto.Auth
                });
                await db.SaveChangesAsync();
            }

            return JRequest.Ok(true);
        }
        catch (Exception exception)
        {
            _logHelper.LogError(exception);
            return JRequest.Ok(false, false, exception.Message);
        }
    }

    private readonly INLogHelper _logHelper;

    public Bg_CreateUserService(INLogHelper logHelper)
    {
        _logHelper = logHelper;
    }
}